package com.zhiche.wms.admin.controller.sys;

import com.baomidou.mybatisplus.plugins.Page;
import com.zhiche.wms.admin.vo.AccountUserVo;
import com.zhiche.wms.admin.vo.sys.ElTreeVO;
import com.zhiche.wms.admin.vo.sys.UserDeliveryPointRequestVO;
import com.zhiche.wms.admin.vo.sys.UserHouseRequestVO;
import com.zhiche.wms.admin.vo.sys.UserRoleRequestVO;
import com.zhiche.wms.core.supports.BaseException;
import com.zhiche.wms.core.supports.RestfulResponse;
import com.zhiche.wms.domain.model.base.Storehouse;
import com.zhiche.wms.domain.model.opbaas.OpDeliveryPoint;
import com.zhiche.wms.domain.model.sys.*;
import com.zhiche.wms.service.sys.IPermissionService;
import com.zhiche.wms.service.sys.IUserDeliveryPointService;
import com.zhiche.wms.service.sys.IUserRoleService;
import com.zhiche.wms.service.sys.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * Created by Nicky on 17/11/24.
 */

@RestController
@RequestMapping(value = "/user", produces = MediaType.APPLICATION_JSON_VALUE)
public class UserController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private IUserService userService;
    @Autowired
    private IUserDeliveryPointService userDeliveryPointService;
    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IUserRoleService userRoleService;

    @PostMapping(value = "/queryPage")
    public RestfulResponse<Page<User>> queryPage(@RequestBody Page<User> page) {
        LOGGER.info("/user/queryPage查询入参page：{}",page);
        RestfulResponse<Page<User>> response = new RestfulResponse<>(0, "success", null);
        Page<User> userPage = userService.selectUserPage(page);
        response.setData(userPage);
        return response;
    }

    /**
     *
     * @param param 禁用主键id
     * @return 禁用是否成功
     */
    @PostMapping(value = "/disableUserInfo")
    public RestfulResponse<String> disableUserInfo(@RequestBody Map<String,Object> param) {
        LOGGER.info("Controller:user/disableUserInfo param: {}", param);
        RestfulResponse<String> result = new RestfulResponse<>(0, "success");
        userService.disableUserInfo(param);
        return result;
    }

    @PostMapping(value = "/create")
    public RestfulResponse<User> create(@RequestBody Map<String, Object> param,
                                        @RequestHeader("Authorization") String auth) {
        RestfulResponse<User> response = new RestfulResponse<>(0, "success", null);
        userService.saveUser(param, auth);
        return response;
    }

    @PostMapping(value = "/update")
    public RestfulResponse<Integer> update(@RequestBody User user) {
        RestfulResponse<Integer> response = new RestfulResponse<>(0, "success");
        try {
            if (userService.updateById(user)) {
                response.setData(1);
            }
        } catch (Exception e) {
            response.setCode(-1);
            response.setMessage(e.getMessage());
        }
        return response;

    }

    @PostMapping("/updatePwd")
    public RestfulResponse<Object> updatePwd(@RequestBody Map<String, Object> param,
                                             @RequestHeader("Authorization") String auth) {
        String result = userService.updatePwd(param, auth);

        return new RestfulResponse<>(0, "修改成功", result);
    }


    @PostMapping(value = "/delete")
    public RestfulResponse<Integer> delete(@RequestBody List<Integer> userIds) {
        RestfulResponse<Integer> response = new RestfulResponse<>(0, "success");
        try {
            if (userService.deleteBatchIds(userIds)) {
                response.setData(1);
            }
        } catch (Exception e) {
            response.setCode(-1);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @GetMapping(value = "/ownRole")
    public RestfulResponse<List<Integer>> listOwnRoleIds(@RequestParam("userId") Integer userId) {
        RestfulResponse<List<Integer>> response = new RestfulResponse<>(0, "success");
        try {
            List<UserRole> userRoleList = userService.listUserRole(userId);
            if (!Objects.equals(userRoleList, null)) {
                List<Integer> roleIds = new ArrayList<>();
                for (UserRole userRole : userRoleList) {
                    roleIds.add(userRole.getRoleId());
                }
                response.setData(roleIds);
            }
        } catch (Exception e) {
            response.setCode(10001);
            response.setMessage(e.getMessage());

        }
        return response;
    }

    @PostMapping(value = "/grantRole")
    public RestfulResponse<Integer> grantRole(@RequestBody UserRoleRequestVO reVO) {
        RestfulResponse<Integer> result = new RestfulResponse<>(0, "success");
        try {
            int i = userService.assignRole(reVO.getUserId(), reVO.getRoleIds());
            result.setData(i);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public RestfulResponse<AccountUserVo> userInfo (@RequestHeader("Authorization") String token) throws
            Exception {
        long startTime = System.currentTimeMillis();
        RestfulResponse<AccountUserVo> result = new RestfulResponse<>(0, "success", null);
        try {
            User user = userService.getLoginUser();
            LOGGER.info("查询到登录用户返回用户信息user：{}",user.toString());

            List<UserRole> roleList = userRoleService.listUserRole(user.getId());
            LOGGER.info("查询到登录用户角色信息 roleList ：{}",roleList);

            List<Storehouse> storehouses = userService.listUserStorehouse(user.getId());
            LOGGER.info("查询到登录用户仓库信息 storehouses ：{}",storehouses);

            if (Objects.isNull(roleList) || roleList.size() == 0) throw new BaseException("用户无角色！");
            AccountUserVo accountUserVo = new AccountUserVo();
            accountUserVo.setAccountCode(user.getCode());
            accountUserVo.setAccountId(user.getId());
            accountUserVo.setMobile(user.getMobile());
            accountUserVo.setTel(user.getMobile());
            accountUserVo.setUserCode(user.getCode());
            accountUserVo.setUserName(user.getName());
            accountUserVo.setUserId(user.getId());
            List<String> roles = new ArrayList<>();
            for (UserRole userRole : roleList) {
                roles.add(userRole.getRoleId().toString());
            }
            accountUserVo.setRoles(roles);
            accountUserVo.setStorehouses(storehouses);
            result.setData(accountUserVo);
        } catch (Exception e) {
            LOGGER.error("UserController.accountInfo ERROR Message : {} ", e.getMessage());
            result.setCode(10003);
            result.setMessage(e.getMessage());
        }
        long endTime = System.currentTimeMillis();
        LOGGER.info("PC端用户登录：总耗时时间 endTime - startTime = {}", (endTime - startTime));
        return result;
    }

    @GetMapping(value = "/firstMenu")
    public RestfulResponse<List<Map>> getFirstDirectory() {

        RestfulResponse<List<Map>> result = new RestfulResponse<>(0, "success");
        User user = userService.getLoginUser();
        List<Permission> firstPermissons = permissionService.listFistPermission(user.getId());
        if (firstPermissons == null || firstPermissons.size() > 0) {
            List<Map> mapList = new ArrayList<>();
            assert firstPermissons != null;
            firstPermissons.forEach(permission -> {
                Map<String, Object> mapPermisson = new HashMap<>();
                mapPermisson.put("id", permission.getId().toString());
                mapPermisson.put("name", permission.getName());
                mapPermisson.put("orders", permission.getOrders());
                mapList.add(mapPermisson);
            });
            result.setData(mapList);
            return result;
        } else {
            result.setCode(100);
            result.setMessage("权限为空");
            return result;
        }
    }


    @GetMapping(value = "/subMenu")
    public RestfulResponse<Map<String, Object>> getSubMenu(@RequestParam("pid") Integer pid) {
        RestfulResponse<Map<String, Object>> result = new RestfulResponse<>(0, "success");
        User user = userService.getLoginUser();
        Map<String, Object> map = new HashMap<>();
        List<Permission> permissionList = permissionService.listChildPermission(user.getId(), pid);
        Permission parentPermission = permissionService.selectById(pid);
        List<Map<String, String>> permMapList = new ArrayList<>();
        if (permissionList != null && permissionList.size() > 0) {
            permissionList.forEach(permission -> {
                Map<String, String> nameMap = new HashMap<>();
                nameMap.put("name", permission.getName());
                permMapList.add(nameMap);
            });
            map.put("parent", parentPermission);
            map.put("children", permMapList);
            result.setData(map);
            return result;
        } else {
            result.setCode(-1);
            result.setMessage("子菜单为空");
            return result;
        }
    }

    @GetMapping(value = "/treeAll")
    public RestfulResponse<List<ElTreeVO>> getSubMenu() {
        RestfulResponse<List<ElTreeVO>> responseBO = new RestfulResponse<>(0, "success");
        List<Permission> listAllPermission = permissionService.selectList(null);
        ElTreeVO elTreeVO = new ElTreeVO();
        elTreeVO.setId(0);
        elTreeVO.setLabel("根权限");
        buildElTree(elTreeVO, listAllPermission);
        responseBO.setData(elTreeVO.getChildren());
        return responseBO;
    }

    private void buildElTree(ElTreeVO elTreeVO, List<Permission> listAllPermission) {
        List<ElTreeVO> children = new ArrayList<>();
        for (Permission permission : listAllPermission) {
            if (permission.getPid().equals(elTreeVO.getId())) {
                ElTreeVO childElTree = new ElTreeVO();
                childElTree.setId(permission.getId());
                childElTree.setLabel(permission.getName());
                buildElTree(childElTree, listAllPermission);
                children.add(childElTree);
            }

            elTreeVO.setChildren(children);
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public RestfulResponse<Boolean> accountLogout() throws Exception {
        RestfulResponse<Boolean> result = new RestfulResponse<>(0, "success", null);
        try {
            result.setData(true);
        } catch (Exception e) {
            LOGGER.error("AccountController.accountLogout ERROR Message : {} ", e.getMessage());
            result.setCode(10003);
            result.setMessage("用户名或口令错误");
        }
        return result;
    }

    /**
     * 获取用户下仓库
     */
    @GetMapping("/listHouses")
    public RestfulResponse<List<Storehouse>> getHousesListByToken() {
        List<Storehouse> list = userService.getHousesListByToken();
        return new RestfulResponse<>(0, "获取仓库关联仓库成功", list);
    }

    @GetMapping(value = "/ownHouses")
    public RestfulResponse<List<String>> listOwnHousesIds(@RequestParam("userId") Integer userId) {
        RestfulResponse<List<String>> response = new RestfulResponse<>(0, "success");
        try {
            List<Storehouse> storehouses = userService.listUserStorehouse(userId);
            if (!Objects.equals(storehouses, null)) {
                List<String> houseIds = new ArrayList<>();
                for (Storehouse storehouse : storehouses) {
                    houseIds.add(storehouse.getId().toString());
                }
                response.setData(houseIds);
            }
        } catch (Exception e) {
            response.setCode(10001);
            response.setMessage(e.getMessage());

        }
        return response;
    }

    @PostMapping(value = "/grantHouse")
    public RestfulResponse<Integer> grantHouse(@RequestBody UserHouseRequestVO reVO) {
        RestfulResponse<Integer> result = new RestfulResponse<>(0, "success");
        try {
            int i = userService.assignHouse(reVO.getUserId(), reVO.getHouseIds());
            result.setData(i);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }

    @GetMapping(value = "/listOwnPoints")
    public RestfulResponse<List<OpDeliveryPoint>> listOwnPoints(@RequestParam("userId") Integer userId) {
        RestfulResponse<List<OpDeliveryPoint>> response = new RestfulResponse<>(0, "success");
        try {
            List<OpDeliveryPoint> points = userService.listUserDeliveryPoint(userId);
            response.setData(points);
        } catch (Exception e) {
            response.setCode(10001);
            response.setMessage(e.getMessage());
        }
        return response;
    }

    @PostMapping(value = "/grantPoint")
    public RestfulResponse<Integer> grantPoint(@RequestBody UserDeliveryPointRequestVO reVO) {
        RestfulResponse<Integer> result = new RestfulResponse<>(0, "success");
        try {
            int i = userService.assignPoint(reVO.getUserId(), reVO.getPoints());
            result.setData(i);
        } catch (Exception e) {
            result.setCode(-1);
            result.setMessage(e.getMessage());
        }
        return result;
    }
}
